'use client';

import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useAuth } from '@/hooks/use-auth';
import { navigationConfig } from '@/config/navigation';
import { useState, useEffect, createElement } from 'react';
import {
  ChevronDown,
  Users,
  Book,
  MessageSquare,
  Bell,
  Award,
  School,
  Settings,
  FileText,
  Calendar,
  Activity,
  GraduationCap,
  UserCheck,
  Building2,
  BellRing,
  BarChart3,
  ShieldCheck,
  Newspaper,
  ScrollText,
  ClipboardCheck,
  ClipboardList,
  Medal,
  PenTool,
  MessageCircle,
  LucideIcon
} from 'lucide-react';

interface SidebarProps {
  isOpen?: boolean;
  onClose?: () => void;
}

const icons: { [key: string]: LucideIcon } = {
  '系统概览': BarChart3,
  '用户管理': Users,
  '管理员管理': ShieldCheck,
  '教师管理': GraduationCap,
  '家长管理': Users,
  '学生管理': UserCheck,
  '班级管理': School,
  '通知管理': BellRing,
  '新闻管理': Newspaper,
  '奖惩管理': Award,
  '待审批': ClipboardList,
  '已审批': ClipboardCheck,
  '奖惩记录': Medal,
  '奖惩提交': Award,
  '成绩录入': PenTool,
  '学校信息': Building2,
  '系统设置': Settings,
  '学习情况': Book,
  '班级活动': Activity,
  '消息中心': MessageSquare,
  '通知公告': Bell,
  '班级概况': Users,
  '作业管理': Book,
  '班级动态': Activity,
  '考勤记录': UserCheck,
  '评价管理': FileText,
  '家长消息': MessageCircle,
};

export function Sidebar({ isOpen: propIsOpen, onClose }: SidebarProps) {
  const { user } = useAuth();
  const pathname = usePathname();
  const [openMenus, setOpenMenus] = useState<string[]>([]);
  const [isMobile, setIsMobile] = useState(false);
  const [isOpen, setIsOpen] = useState(true);

  const items = user ? navigationConfig[user.role] : [];

  useEffect(() => {
    const checkMobile = () => {
      setIsMobile(window.innerWidth < 1024);
      setIsOpen(window.innerWidth >= 1024);
    };

    checkMobile();
    window.addEventListener('resize', checkMobile);
    return () => window.removeEventListener('resize', checkMobile);
  }, []);

  useEffect(() => {
    if (isMobile && propIsOpen !== undefined) {
      setIsOpen(propIsOpen);
    }
  }, [propIsOpen, isMobile]);

  const toggleMenu = (href: string) => {
    setOpenMenus(prev => 
      prev.includes(href) 
        ? prev.filter(item => item !== href)
        : [...prev, href]
    );
  };

  const isActive = (href: string) => pathname === href;
  const isMenuOpen = (href: string) => openMenus.includes(href);

  if (!user) return null;

  const sidebarContent = (
    <>
      <div className="p-6 border-b">
        <h2 className="text-xl font-bold">家校通系统</h2>
        <p className="text-sm text-gray-500 mt-2">{user.name} - {user.role}</p>
      </div>
      <nav className="flex-1 overflow-y-auto">
        <ul className="p-4 space-y-2">
          {items.map((item) => (
            <li key={item.href}>
              {item.children ? (
                <div className="space-y-1">
                  <button
                    onClick={() => toggleMenu(item.href)}
                    className={`
                      flex items-center w-full px-4 py-2 text-sm font-medium rounded-md
                      transition-colors hover:bg-gray-100
                      ${isMenuOpen(item.href) ? 'bg-gray-100' : ''}
                    `}
                  >
                    {icons[item.label] && (
                      <span className="mr-3">
                        {createElement(icons[item.label], { className: "h-5 w-5" })}
                      </span>
                    )}
                    {item.label}
                    <ChevronDown
                      className={`
                        ml-auto h-4 w-4 transition-transform duration-200
                        ${isMenuOpen(item.href) ? 'rotate-180' : ''}
                      `}
                    />
                  </button>
                  <div
                    className={`
                      pl-4 space-y-1 overflow-hidden transition-all duration-200
                      ${isMenuOpen(item.href) ? 'max-h-96' : 'max-h-0'}
                    `}
                  >
                    {item.children.map((child) => (
                      <Link
                        key={child.href}
                        href={child.href}
                        className={`
                          block px-4 py-2 text-sm rounded-md transition-colors
                          hover:bg-gray-100
                          ${isActive(child.href) ? 'bg-blue-50 text-blue-600' : 'text-gray-600'}
                        `}
                      >
                        {child.label}
                      </Link>
                    ))}
                  </div>
                </div>
              ) : (
                <Link
                  href={item.href}
                  className={`
                    flex items-center px-4 py-2 text-sm font-medium rounded-md
                    transition-colors hover:bg-gray-100
                    ${isActive(item.href) ? 'bg-blue-50 text-blue-600' : 'text-gray-600'}
                  `}
                >
                  {icons[item.label] && (
                    <span className="mr-3">
                      {createElement(icons[item.label], { className: "h-5 w-5" })}
                    </span>
                  )}
                  {item.label}
                </Link>
              )}
            </li>
          ))}
        </ul>
      </nav>
    </>
  );

  if (isMobile) {
    return (
      <>
        <div
          className={`
            fixed inset-0 z-40 bg-background/80 backdrop-blur-sm transition-opacity duration-300
            ${isOpen ? 'opacity-100' : 'opacity-0 pointer-events-none'}
          `}
          onClick={onClose}
        />
        <div
          className={`
            fixed top-14 left-0 z-50 h-[calc(100vh-3.5rem)] w-64 bg-white shadow-lg
            transition-transform duration-300 ease-in-out
            ${isOpen ? 'translate-x-0' : '-translate-x-full'}
          `}
        >
          {sidebarContent}
        </div>
      </>
    );
  }

  return (
    <div className="hidden lg:flex flex-col w-64 border-r bg-white">
      {sidebarContent}
    </div>
  );
} 